//
//  MHWebViewController.m
// MiaoCircle
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHWebViewController.h"
#import "FBKVOController+MHExtension.h"
#import "UIScrollView+MHRefresh.h"
#import "MHQRCodeModel.h"
#import "MLCircleInfoMainPageViewModel.h"
#import "MHshareRecent.h"
#import "zhWallView.h"
#import "MHRewardActivityInfo.h"
#import "MHFuQian.h"
/// KVO 监听的属性
/// 加载情况
static NSString * const MHWebViewKVOLoading = @"loading";
/// 文章标题
static NSString * const MHWebViewKVOTitle = @"title";
/// 进度
static NSString * const MHWebViewKVOEstimatedProgress = @"estimatedProgress";

@interface MHWebViewController ()
/// webView
@property (nonatomic, weak, readwrite) WKWebView *webView;
/// 进度条
@property (nonatomic, readwrite, strong) UIProgressView *progressView;
/// 返回按钮
@property (nonatomic, readwrite, strong) UIBarButtonItem *backItem;


@property (nonatomic, readwrite, strong) UIBarButtonItem *shareItem;
/// 关闭按钮 （点击关闭按钮  退出WebView）
@property (nonatomic, readwrite, strong) UIBarButtonItem *closeItem;
/// viewModel
@property (nonatomic, strong, readonly) MHWebViewModel *viewModel;
@property(nonatomic, strong) UIButton *applayButton;

@end

@implementation MHWebViewController
{
    /// KVOController 监听数据
    FBKVOController *_KVOController;
}

@dynamic viewModel;

- (void)dealloc{
    MHDealloc;
    /// remove observer ,otherwise will crash
    [_webView stopLoading];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar addSubview:self.progressView];
    
    if (!self.viewModel.translucentNavigationBar) {
        [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setShadowImage:[UIImage new]];
        self.navigationController.navigationBar.translucent = NO;
      
    }else
    {
        NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
        textAttrs[NSFontAttributeName] =  MHMediumFont(FontSizeFromPixel(24));
        textAttrs[NSForegroundColorAttributeName] = [UIColor whiteColor];
        [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
    }
    /// 加载请求数据
    [self.webView loadRequest:self.viewModel.request];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    if(self.viewModel.translucentNavigationBar)
    {
         return UIStatusBarStyleLightContent;
    }else
    {
         return UIStatusBarStyleDefault;
    }
   
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.progressView removeFromSuperview];
    
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSFontAttributeName] =  MHMediumFont(FontSizeFromPixel(24));
    textAttrs[NSForegroundColorAttributeName] = MHTextColor333;
    [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    /// 添加断言，request错误 应用直接crash
    NSParameterAssert(self.viewModel.request);
    
    
    self.navigationItem.leftBarButtonItem = self.backItem;
    
    self.webView.scrollView.bounces = false;
    ///设置userAgent;
    NSString *userAgent = @"miaodongquan_ios";
    
    if (!(MHIOSVersion>=9.0)) [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"userAgent":userAgent}];
    
    /// 注册JS
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    /// 这里可以注册JS的处理 涉及公司私有方法 这里笔者不作处理
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    // CoderMikeHe Fixed : 自适应屏幕宽度js
    NSString *jsString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('minimum-scale', '1.0');meta.setAttribute('initial-scale', '1.0'); meta.setAttribute('maximum-scale', '1.0'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    // 添加自适应屏幕宽度js调用的方法
    [userContentController addUserScript:userScript];
    /// 赋值userContentController
    configuration.userContentController = userContentController;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:MH_SCREEN_BOUNDS configuration:configuration];
    
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    
    if ((MHIOSVersion >= 9.0)) webView.customUserAgent = userAgent;
    self.webView = webView;
    [self.view addSubview:webView];
    
    /// oc调用js
    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"navigator.userAgent.result is ++++ %@", result);
    }];
    
    /// 监听数据
    _KVOController = [FBKVOController controllerWithObserver:self];
    @weakify(self);
    /// binding self.viewModel.avatarUrlString
    [_KVOController mh_observe:self.webView keyPath:MHWebViewKVOTitle block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        @strongify(self);
        /// CoderMikeHe FIXED: 这里只设置导航栏的title 以免self.title 设置了tabBarItem.title
        if (!self.viewModel.shouldDisableWebViewTitle) self.navigationItem.title = self.webView.title;
    }];
    [_KVOController mh_observe:self.webView keyPath:MHWebViewKVOLoading block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        NSLog(@"--- webView is loading ---");
    }];
    
    [_KVOController mh_observe:self.webView keyPath:MHWebViewKVOEstimatedProgress block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
        @strongify(self);
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        if(self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }];
    
    /// 添加刷新控件
    if(self.viewModel.shouldPullDownToRefresh){
        [self.webView.scrollView mh_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
            @strongify(self);
            [self.webView reload];
        }];
        [self.webView.scrollView.mj_header beginRefreshing];
    }
    self.webView.scrollView.contentInset = self.contentInset;
    
    /// CoderMikeHe: 适配 iPhone X + iOS 11，去掉安全区域
    if (@available(iOS 11.0, *)) {
        MHAdjustsScrollViewInsets_Never(webView.scrollView);
    }
   self.webView.scrollView.showsHorizontalScrollIndicator = NO;
   self.webView.scrollView.bouncesZoom = NO;
    
    
}

-(void) applyButtonClick
{
    
}

#pragma mark - 事件处理
- (void)_backItemDidClicked{ /// 返回按钮事件处理
    /// 可以返回到上一个网页，就返回到上一个网页
    if (self.webView.canGoBack) {
        [self.webView goBack];
    }else{/// 不能返回上一个网页，就返回到上一个界面
        /// 判断 是Push还是Present进来的，
        if (self.presentingViewController) {
            [self.viewModel.services dismissViewModelAnimated:YES completion:NULL];
        } else {
            [self.viewModel.services popViewModelAnimated:YES];
        }
    }
}

-(void)_shareItemClick
{
    [[self.viewModel.shareCommand execute:nil] subscribeNext:^(MHRewardActivityInfo *info) {
        self.zh_popupController = [zhPopupController new];
        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
        zhWallView *wallView =  [self wallView];
        MHshareRecent *recent = [MHshareRecent new];
        if (info.circleName.length >= 6) {
           info.circleName = [info.circleName substringWithRange:NSMakeRange(0, 6)];
        }
        recent.title = [NSString stringWithFormat:@"%@--招募新成员!",info.circleName];
        recent.intro = [AXAppDelegate sharedDelegate].currentCircleInfo.intro.length > 0 ? [AXAppDelegate sharedDelegate].currentCircleInfo.intro : @"百唠期待你的加入";
        recent.coverUrl = [AXAppDelegate sharedDelegate].currentCircleInfo.fullCoverUrl;
        
        NSString *redirectUrl = [NSString stringWithFormat:@"%@join-circle.html?circleId=%ld&userid=%ld&userKey=%@",[MHConfigureManager h5BaseUrl],info.circleId,[MHHTTPService sharedInstance].currentUser.userId,[MHHTTPService sharedInstance].currentUser.userKey];
        NSString *ecodeUrl = [self urlEncodeUsingEncoding:NSUTF8StringEncoding string:redirectUrl];
        
        
        
        NSString *url =  [NSString stringWithFormat:@"http://zg.miaodongquan.com/get-weixin-code.html?appid=wx97ea250bca340197&scope=snsapi_userinfo&state=&redirect_uri=%@",ecodeUrl];
       
        recent.webUrl = url;
        wallView.models = [self shareWallShareModel:recent];
        [wallView autoAdjustFitHeight];
        @weakify(self);
        wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
            @strongify(self);
            [self.zh_popupController dismiss];
        };
        [self.zh_popupController presentContentView:wallView];
    }];
   
}


- (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding string:(NSString *) string
{
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
                                                                                 NULL,
                                                                                 (__bridge CFStringRef)string,
                                                                                 NULL,
                                                                                 (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                 CFStringConvertNSStringEncodingToEncoding(encoding)));
}

- (NSArray *)shareWallShareModel:(MHshareRecent *)recent{
    
    
    __weak __typeof(self)weakSelf = self;
    VoidBlock_id_int shareFriend =  ^(UIButton *button, int index) {
        
        [weakSelf.zh_popupController dismiss];
        [MHMomentHelper shareWithSharRecent:recent shareType:MHCirclShareTypeWeChat];
    };
    
    VoidBlock_id_int shareTimeLine =  ^(UIButton *button, int index) {
        [weakSelf.zh_popupController dismiss];
        [MHMomentHelper shareWithSharRecent:recent shareType:MHCirclShareTypeWeChatTimeLine];
    };
    NSArray *arr1 = @[
                      
                      @{titleKey   : @"微信",
                        imgNameKey : @"icon_share_wechat",
                        excutesCustomBlock: shareFriend,
                        
                        },
                      
                      @{titleKey   : @"微信朋友圈",
                        imgNameKey : @"icon_share_timeline",
                        excutesCustomBlock: shareTimeLine,
                        
                        },
                      ];
    
    
    
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dict in arr1) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        int index =  [arr1 indexOfObject:dict];
        [array1 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    
    return [NSMutableArray arrayWithObjects:array1, nil];
}

- (void)_closeItemDidClicked{
    /// 判断 是Push还是Present进来的
    if (self.presentingViewController) {
        [self.viewModel.services dismissViewModelAnimated:YES completion:NULL];
    } else {
        [self.viewModel.services popViewModelAnimated:YES];
    }
}

- (UIEdgeInsets)contentInset{
    if (self.viewModel.translucentNavigationBar) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else
        
    {
        return UIEdgeInsetsMake(MH_APPLICATION_TOP_BAR_HEIGHT, 0, 0, 0);
    }
    
}

-(void)rightButtonClick
{
    @weakify(self);
    if (self.viewModel.showRightShareJoinTitle) {
        [MHMomentHelper enterOrJionCircleWithViewModel:self.viewModel];
//        if([AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle)
//        {
//            //                    MHCircleHomeModel *circle = self.circles[indexPath.row];
//            MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//            [self.viewModel.services pushViewModel:viewModel animated:YES];
//        }else
//        {
//            if ([AXAppDelegate sharedDelegate].currentDiscoverModel.payType == 2) {
//
//
//                [[self.viewModel.fetchQrCodeLinkCommond  execute:nil] subscribeNext:^(MHQRCodeModel *qrCodeModel) {
//                    OSMessage *msg=[[OSMessage alloc] init];
//                    msg.title=qrCodeModel.title;
//                    msg.link = qrCodeModel.webUrl;
//                    msg.desc = qrCodeModel.intro;
//                    NSURL *url = [NSURL URLWithString:qrCodeModel.coverUrl];
//                    NSData *data = [NSData dataWithContentsOfURL:url];
//                    UIImage *img = [[UIImage alloc] initWithData:data];
//                    UIImage *thumbImage;
//                    if (img) {
//                        thumbImage = img;
//                    }else
//                    {
//                        thumbImage = [UIImage imageNamed:@"AppIcon"];
//                    }
//                    NSData *compressData = [thumbImage compressWithLengthLimit:31 *1024];
//                    msg.image = compressData;
//                    [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
//
//                    } Fail:^(OSMessage *message, NSError *error) {
//                    }];
//                }];
//            }else
//            {
//
//                LCActionSheet *sheet = [LCActionSheet sheetWithTitle:[NSString stringWithFormat:@"确定加入%@",[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName] cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
//                    if (buttonIndex == 0) return;
//                    @strongify(self);
//                    @weakify(self);
//                    [[self.viewModel.applyCommand execute:nil] subscribeNext:^(MHHTTPResponse *respose) {
//                        @strongify(self);
//                        [MBProgressHUD mh_showTips:@"加入成功"];
//                        [AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle = true;
//                        [MHNotificationCenter postNotificationName:MHReloadFirstPageDataNotification object:nil];
//                        [MHNotificationCenter postNotificationName:MHReloadHomeDiscoverDataNotification object:nil];
//
//                        MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//                        [self.viewModel.services pushViewModel:viewModel animated:YES];
//                    }];
//
//
//                } otherButtonTitles:@"确定", nil];
//                NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
//                [indexSet addIndex:1];
//                sheet.destructiveButtonIndexSet = indexSet;
//                [sheet show];
//
//            }
//        }
    }
}


-(void)bindViewModel
{
    [super bindViewModel];
    @weakify(self);
    [RACObserve(self.viewModel, showBottomButton) subscribeNext:^(NSNumber *show) {
        @strongify(self);
        BOOL showBottom = [show boolValue];
        self.applayButton.hidden  = !showBottom;
        CGFloat bottomMargin = 50 +zh_safeAreaHeight();
        self.webView.mh_height = showBottom ? MH_SCREEN_HEIGHT - bottomMargin: MH_SCREEN_HEIGHT;
        
        if (showBottom && !self.applayButton) {
            UIButton *applyBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, MH_SCREEN_HEIGHT - bottomMargin, MH_SCREEN_WIDTH , bottomMargin -zh_safeAreaHeight())];
            [applyBtn setBackgroundColor:MHButtonBlueBgColor];
            if ([AXAppDelegate sharedDelegate].currentDiscoverModel.payType == 2) {
                [applyBtn setImage:[UIImage imageNamed:@"discover_pay"] forState:0];
                [applyBtn setImageEdgeInsets:UIEdgeInsetsMake(0.0, -10, 0.0, 0.0)];
            }
            [applyBtn setTitle:[AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle ? @"进入圈子":@"申请加入" forState:0];
            applyBtn.titleLabel.textColor = MHWhiteTextColor;
            
            [applyBtn addTarget:self action:@selector(applyButtonClick) forControlEvents:UIControlEventTouchDown];
            [applyBtn addTarget:self action:@selector(applyButtonClick) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
            [self.view addSubview:applyBtn];
            self.applayButton = applyBtn;
            @weakify(self);
            [applyBtn bk_whenTapped:^{
                @strongify(self);
                //加入圈子处理，付费圈子分享;
                
                if([AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle)
                {
                    
                    [MHMomentHelper redirectToGroupChatWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId service:self.viewModel.services groupId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleCode title:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName];
                    //                    MHCircleHomeModel *circle = self.circles[indexPath.row];
//                    MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//                    [self.viewModel.services pushViewModel:viewModel animated:YES];
                }else
                {
                    if ([AXAppDelegate sharedDelegate].currentDiscoverModel.payType == 2) {
                        
                        if([AXAppDelegate sharedDelegate].isAuthorizationExpired)
                        {
                            [[[MHHTTPService sharedInstance] appFuQinJoinCircleWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId openid:@"" inviteUserKey:@""] subscribeNext:^(MHFuQian *fuqian) {
                                [OpenShare OpenUrlLink:fuqian.urlScheme Success:^(NSDictionary *message) {
                                    
                                } Fail:^(NSDictionary *message, NSError *error) {
                                    
                                }];
                            }];
                        }else
                        {
                            [[self.viewModel.fetchQrCodeLinkCommond  execute:nil] subscribeNext:^(MHQRCodeModel *qrCodeModel) {
                                OSMessage *msg=[[OSMessage alloc] init];
                                msg.title=qrCodeModel.title;
                                msg.link = qrCodeModel.webUrl;
                                msg.desc = qrCodeModel.intro;
                                NSURL *url = [NSURL URLWithString:qrCodeModel.coverUrl];
                                NSData *data = [NSData dataWithContentsOfURL:url];
                                UIImage *img = [[UIImage alloc] initWithData:data];
                                UIImage *thumbImage;
                                if (img) {
                                    thumbImage = img;
                                }else
                                {
                                    thumbImage = [UIImage imageNamed:@"AppIcon"];
                                }
                                NSData *compressData = [thumbImage compressWithLengthLimit:31 *1024];
                                msg.image = compressData;
                                [OpenShare shareToWeixinSession:msg Success:^(OSMessage *message) {
                                    
                                } Fail:^(OSMessage *message, NSError *error) {
                                }];
                            }];
                        }
                        
                    }else
                    {
                        
                        LCActionSheet *sheet = [LCActionSheet sheetWithTitle:[NSString stringWithFormat:@"确定加入%@",[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName] cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
                            if (buttonIndex == 0) return;
                            @strongify(self);
                            [[self.viewModel.applyCommand execute:nil] subscribeNext:^(MHHTTPResponse *respose) {
                                [MBProgressHUD mh_showTips:@"加入成功"];
                                [AXAppDelegate sharedDelegate].currentDiscoverModel.isInCircle = true;
                                [MHNotificationCenter postNotificationName:MHReloadFirstPageDataNotification object:nil];
                                [MHNotificationCenter postNotificationName:MHReloadHomeDiscoverDataNotification object:nil];
                                [MHNotificationCenter postNotificationName:MHReloadDiscoverHomeCircleDataNotification object:nil];
                                [applyBtn setTitle:@"进入圈子" forState:0];
                                
                                
                                [MHMomentHelper redirectToGroupChatWithCircleId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleId service:self.viewModel.services groupId:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleCode title:[AXAppDelegate sharedDelegate].currentDiscoverModel.circleName];
                                
//                                MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelIDKey:@([AXAppDelegate sharedDelegate].currentDiscoverModel.circleId)}];
//                                [self.viewModel.services pushViewModel:viewModel animated:YES];
                                
                            }];
                            
                        } otherButtonTitles:@"确定", nil];
                        NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
                        [indexSet addIndex:1];
                        sheet.destructiveButtonIndexSet = indexSet;
                        [sheet show];
                        
                    }
                }
                
                
            }];
        }
        
    }];
    //    if (self.viewModel.showBottomButton) {
    //
    //    }
    
}



#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    /// js call OC function
    
}

#pragma mark - WKNavigationDelegate
/// 内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    /// 不显示关闭按钮
    if (self.viewModel.showRightShareIcon) {
        [self.navigationItem setRightBarButtonItem:self.shareItem];
        self.progressView.hidden = YES;
    }
    
    if(self.viewModel.shouldDisableWebViewClose) return;
    
    UIBarButtonItem *backItem = self.navigationItem.leftBarButtonItems.firstObject;
    if (backItem) {
        if ([self.webView canGoBack]) {
            [self.navigationItem setLeftBarButtonItems:@[backItem, self.closeItem]];
        } else {
            [self.navigationItem setLeftBarButtonItem:backItem];
        }
    }
}

// 导航完成时，会回调（也就是页面载入完成了）
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    if (self.viewModel.shouldPullDownToRefresh) [webView.scrollView.mj_header endRefreshing];
}

// 导航失败时会回调
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    if (self.viewModel.shouldPullDownToRefresh) [webView.scrollView.mj_header endRefreshing];
}

// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //
    NSURL *url =   navigationAction.request.URL;
    NSLog(@"navigationAction.request.URL:   %@", navigationAction.request.URL);
    self.viewModel.showBottomButton = [navigationAction.request.URL.absoluteString containsString:@"join-circle-app"];
//    if(url.scheme!= nil)
//    {
//        if ([url.scheme isEqualToString:@"weixin"]) {
//            decisionHandler(WKNavigationActionPolicyCancel);
//            return;
//        }
//    }
    decisionHandler(WKNavigationActionPolicyAllow);
}


//-(void) catchEventWithUrl:(NSURL *) url
//{
//    if([url.host isEqualToString:@"wap"])
//    {
//        if ([url.relativePath isEqualToString:@"/pay"]) {
//            if ([[UIApplication sharedApplication] canOpenURL:url]) {
//                if (@available(iOS 10, *)) {
//                    [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly :@"false"} completionHandler:nil];
//                }else
//                {
//                    [[UIApplication sharedApplication] openURL:url];
//                }
//            }
//        }
//    }
//}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {
    NSURLCredential *cred = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
}

#pragma mark - WKUIDelegate
- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    /// CoderMike Fixed : 解决点击网页的链接 不跳转的Bug。
    WKFrameInfo *frameInfo = navigationAction.targetFrame;
    if (![frameInfo isMainFrame]) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark runJavaScript
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    [NSObject mh_showAlertViewWithTitle:nil message:message confirmTitle:@"我知道了"];
    completionHandler();
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    completionHandler(YES);
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
    completionHandler(defaultText);
}



#pragma mark - Getter & Setter
- (UIProgressView *)progressView {
    if (!_progressView) {
        CGFloat progressViewW = MH_SCREEN_WIDTH;
        CGFloat progressViewH = 3;
        CGFloat progressViewX = 0;
        CGFloat progressViewY = CGRectGetHeight(self.navigationController.navigationBar.frame) - progressViewH + 1;
        UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(progressViewX, progressViewY, progressViewW, progressViewH)];
        progressView.progressTintColor = MH_MAIN_TINTCOLOR;
        progressView.trackTintColor = [UIColor clearColor];
        [self.view addSubview:progressView];
        self.progressView = progressView;
    }
    return _progressView;
}


- (UIBarButtonItem *)backItem
{
    if (_backItem == nil) {
        if (self.viewModel.hiddenNavBack) {
            _backItem = nil;
        }else
        {
            _backItem = [UIBarButtonItem mh_backItemWithTitle:@"" imageName:self.viewModel.translucentNavigationBar ? @"icon_back" : @"barbuttonicon_back_15x30" target:self action:@selector(_backItemDidClicked)];
        }
    }
    return _backItem;
}


- (UIBarButtonItem *)shareItem
{
    if (_shareItem == nil) {
        _shareItem = [UIBarButtonItem mh_backItemWithTitle:@"" imageName:@"discover_sharemore" target:self action:@selector(_shareItemClick)];
    }
    return _shareItem;
}


- (UIBarButtonItem *)closeItem {
    if (!_closeItem) {
        _closeItem = [UIBarButtonItem mh_systemItemWithTitle:@"关闭" titleColor:nil imageName:nil target:self selector:@selector(_closeItemDidClicked) textType:YES];
    }
    return _closeItem;
}



@end
